//
//  KDCalendarController.m
//  WangJingApp
//
//  Created by 魏强 on 17/1/10.
//  Copyright © 2017年 KDTech. All rights reserved.
//  管理日历板块

#import "KDCalendarController.h"
#import "FSCalendar.h"
#import "KDRectanglesProgress.h"
#import "WQSeparatorView.h"
#import "KDManageRequestTool.h"
#import "KDMyUnit.h"
#import "KDSubordinateUnit.h"
#import "KDSubmissionUnit.h"
#import "SVProgressHUD.h"
#import "SCChart.h"
#define KDTop2MsgColor WQColor(251, 182, 64)
#define KDTop3MsgColor WQColor(46, 183, 242)
#define KDTop1MsgColor WQColor(252, 101, 116)
#define KDOtherMsgColor WQColor(203, 203, 203)
@interface KDCalendarController ()<FSCalendarDataSource, FSCalendarDelegate, UIScrollViewDelegate>
@property (nonatomic, retain) NSDateFormatter *fmt;
@property (weak, nonatomic) IBOutlet FSCalendar *calendar;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *calendarHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *calendarWidthConstraint;
/**  在岗率进度条 */
@property (weak, nonatomic) IBOutlet KDRectanglesProgress *onDutyPesentageView;
/**  本单位信息报送彩分率 */
@property (weak, nonatomic) IBOutlet KDRectanglesProgress *selfPostMessagePesentageView;
/**  志愿者信息报送采分率 */
@property (weak, nonatomic) IBOutlet KDRectanglesProgress *volunteerPostMessagePesentageView;

/**  scrollView的宽度约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollView_cons_w;
/**  scrollView的高度约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollView_Cons_h;

/**  tabBar原始y */
@property (nonatomic, assign) CGFloat originalTabY;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/**  上一次的滑动位置 */
@property (nonatomic, assign) float lastContentOffset;
/**  <#Description#> */
@property (nonatomic, weak) CAGradientLayer* gradientLayer;

@property (weak, nonatomic) IBOutlet WQSeparatorView *firstView;
@property (weak, nonatomic) IBOutlet WQSeparatorView *secondView;
@property (weak, nonatomic) IBOutlet WQSeparatorView *thirdView;
/**  单位总人数lb */
@property (weak, nonatomic) IBOutlet UILabel *totalPerLb;
/**  pc端在线人数 */
@property (weak, nonatomic) IBOutlet UILabel *pcPer;
/**  志愿者已报送 */
@property (weak, nonatomic) IBOutlet UILabel *volunteerSubmissionLb;
/**  志愿者采分 */
@property (weak, nonatomic) IBOutlet UILabel *volunteerAcceptedLb;
/**  单位已报送 */
@property (weak, nonatomic) IBOutlet UILabel *unitSubmissionLb;
/**  单位已采分 */
@property (weak, nonatomic) IBOutlet UILabel *infoAcceptedLb;
/*************************  下辖单位 *************************/
/**  下辖单位总人数 */
@property (weak, nonatomic) IBOutlet UILabel *subTotalPerLb;
/**  下辖pc端在线人数 */
@property (weak, nonatomic) IBOutlet UILabel *subPcPer;
/**  下辖总体上报信息 */
@property (weak, nonatomic) IBOutlet UILabel *totalSubmissionLb;
/**  下辖被采分 */
@property (weak, nonatomic) IBOutlet UILabel *subInfoAcceptedLb;

/**  本单位信息集合 */
@property (nonatomic, strong) KDMyUnit *myUnit;

/**  下辖单位集合 */
@property (nonatomic, strong) KDSubordinateUnit *subordinateUnit;
/**  top1分数 */
@property (weak, nonatomic) IBOutlet UILabel *top1ScoreLb;
@property (weak, nonatomic) IBOutlet UIButton *top1ScoreBtn;

/**  top2分数 */
@property (weak, nonatomic) IBOutlet UILabel *top2ScoreLb;
@property (weak, nonatomic) IBOutlet UIButton *top2ScoreBtn;

/**  top3分数 */
@property (weak, nonatomic) IBOutlet UILabel *top3ScoreLb;
@property (weak, nonatomic) IBOutlet UIButton *top3ScoreBtn;

/**  top1单位 */
@property (weak, nonatomic) IBOutlet UILabel *top1UnitLb;
@property (weak, nonatomic) IBOutlet UILabel *top2UnitLb;
@property (weak, nonatomic) IBOutlet UILabel *top3unitLb;
/**  饼状图 */
@property (nonatomic, weak) SCPieChart *chartView;
@property (weak, nonatomic) IBOutlet UIView *pieChartUnderView;
@property (weak, nonatomic) IBOutlet UILabel *top1SubmissionLb;
@property (weak, nonatomic) IBOutlet UILabel *top2SubmissionLb;
@property (weak, nonatomic) IBOutlet UILabel *top3SubmissionLb;
@property (weak, nonatomic) IBOutlet UILabel *otherSubmissionLb;


/********************  志愿者部分 *******************************/
/**  志愿者注册总人数 */
@property (weak, nonatomic) IBOutlet UILabel *volunteerTotalCountLb;
/**  登录人数 */
@property (weak, nonatomic) IBOutlet UILabel *volLoginCountLb;
@property (weak, nonatomic) IBOutlet UILabel *top1VolunteerLb;
@property (weak, nonatomic) IBOutlet UILabel *top2VolunteerLb;
@property (weak, nonatomic) IBOutlet UILabel *top3VolunteerLb;
@property (weak, nonatomic) IBOutlet UILabel *top1VolunteerAddLb;
@property (weak, nonatomic) IBOutlet UILabel *top2VolunteerAddLb;
@property (weak, nonatomic) IBOutlet UILabel *top3VolunteerAddLb;
/**  选中的日期 */
@property (nonatomic, copy) NSString * selectDateStr;

@end

@implementation KDCalendarController
#pragma mark - 懒加载区
- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"yyyyMMdd";
    }
    return _fmt;
}

#pragma mark - 生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectDateStr = [self.fmt stringFromDate:[NSDate date]];
    [self setupPersentage];
    [self setupSeparator];
    
    self.originalTabY = self.tabBarController.tabBar.y;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupBlur];
    //[self loadData];
    
    //    self.onDutyPesentageView
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _calendar.scope = FSCalendarScopeWeek;
    self.scrollView_cons_w.constant = screenW;
}
#pragma mark - 板块布置区
- (void)setupPersentage{
    self.onDutyPesentageView.color = WQColor(251, 182, 64);
    self.onDutyPesentageView.persentage = 0.45;
    self.volunteerPostMessagePesentageView.color = WQColor(52, 220, 172);
    self.volunteerPostMessagePesentageView.persentage = 0.35;
    self.selfPostMessagePesentageView.color = WQColor(46, 183, 242);
    self.selfPostMessagePesentageView.persentage = 0.25;
}

- (void)setupSeparator{
    self.firstView.separatorMode = WQViewSeparatorModeTopAndBottom;
    self.firstView.separatorColor = WQColor(218, 218, 218);
    self.secondView.separatorMode = WQViewSeparatorModeTopAndBottom;
    self.secondView.separatorColor = WQColor(218, 218, 218);
    self.thirdView.separatorMode = WQViewSeparatorModeTopAndBottom;
    self.thirdView.separatorColor = WQColor(218, 218, 218);
}


/**
 *  给日历设置毛玻璃效果
 */
- (void)setupBlur{
    //1.设置底部渐变色
    //初始化CAGradientlayer对象，使它的大小为UIView的大小
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    self.gradientLayer = gradientLayer;
    self.gradientLayer.frame = self.calendar.bounds;
    //    KDLog(@"%@", NSStringFromCGRect(self.gradientLayer.bounds));
    //将CAGradientlayer对象添加在我们要设置背景色的视图的layer层
    [self.calendar.layer insertSublayer:self.gradientLayer atIndex:0];
    
    //设置渐变区域的起始和终止位置（范围为0-1）
    self.gradientLayer.startPoint = CGPointMake(0, 0);
    self.gradientLayer.endPoint = CGPointMake(0, 1);
    
    //设置颜色数组
    self.gradientLayer.colors = @[(__bridge id)WQColor(149, 156, 155).CGColor,
                                  (__bridge id)WQColor(53 , 58, 67).CGColor];
    
    //设置颜色分割点（范围：0-1）
    self.gradientLayer.locations = @[@(0), @(1.0f)];
    
    //2.设置底部毛玻璃效果
    if (!UIAccessibilityIsReduceTransparencyEnabled()) {
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        blurEffectView.frame = self.calendar.bounds;
        blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//        self.calendar.clipsToBounds
        [self.calendar insertSubview:blurEffectView atIndex:0];
    }
}
- (void)setupPieChartView{
    KDSubmissionUnit *unit1;
    KDSubmissionUnit *unit2;
    KDSubmissionUnit *unit3;
    if (self.subordinateUnit.subordinateSubmission.submissionCountTop.count) {
        unit1 = self.subordinateUnit.subordinateSubmission.submissionCountTop[0];
        unit2 = self.subordinateUnit.subordinateSubmission.submissionCountTop[1];
        unit3 = self.subordinateUnit.subordinateSubmission.submissionCountTop[2];
    }else{
        unit1 = [[KDSubmissionUnit alloc]init];
        unit1.mark = 0;
        unit1.check_desc = @"无";
        unit2 = [[KDSubmissionUnit alloc]init];
        unit2.mark = 0;
        unit2.check_desc = @"无";
        unit3 = [[KDSubmissionUnit alloc]init];
        unit3.mark = 0;
        unit3.check_desc = @"无";
    }
    NSInteger totalSubmission = (self.subordinateUnit.subordinateSubmission.totalSubmission)?self.subordinateUnit.subordinateSubmission.totalSubmission:1;

    CGFloat value1 = 100 * unit1.mark/(totalSubmission *1.0);
    CGFloat value2 = 100 * unit2.mark/(totalSubmission *1.0);
    CGFloat value3 = 100 * unit3.mark/(totalSubmission *1.0);
    CGFloat value4 =( 100 - value1 - value2 - value3);
    
    
    value4 = (value4>=0) ? value4:0;
    self.top1SubmissionLb.text = [NSString stringWithFormat:@"%@  %ld条",unit1.check_desc, (long)unit1.mark];
    self.top2SubmissionLb.text = [NSString stringWithFormat:@"%@  %ld条",unit2.check_desc, (long)unit2.mark];
    self.top3SubmissionLb.text = [NSString stringWithFormat:@"%@  %ld条",unit3.check_desc, (long)unit3.mark];
    self.otherSubmissionLb.text = [NSString stringWithFormat:@"其他单位  %d条",(int)value4*100];
    if (!self.chartView) {
        NSArray *items = @[[SCPieChartDataItem dataItemWithValue:value3 color:KDTop3MsgColor description:nil],
                           [SCPieChartDataItem dataItemWithValue:value1 color:KDTop1MsgColor description:nil],
                           [SCPieChartDataItem dataItemWithValue:value2 color:KDTop2MsgColor description:nil],
                           [SCPieChartDataItem dataItemWithValue:value4 color:KDOtherMsgColor description:nil],
                           ];
        [self setUpChartViewWithArr:items];
        }else{
            NSArray *ary = @[[NSString stringWithFormat:@"%f",value3],[NSString stringWithFormat:@"%f",value1],[NSString stringWithFormat:@"%f",value2],[NSString stringWithFormat:@"%f",value4]];
            [self.chartView updateChartByNumbers:ary];
    }
    
}
- (void)setUpChartViewWithArr:(NSArray *)items{
    
    CGFloat height = self.pieChartUnderView.height;
    SCPieChart *  chartView= [[SCPieChart alloc] initWithFrame: CGRectMake((screenW - height) *0.5 , 0, height, height) items:items];
    //    KDLog(@"%@", NSStringFromCGRect(chartView.frame));
    self.chartView = chartView;
    chartView.descriptionTextColor = [UIColor whiteColor];
    chartView.descriptionTextFont  = [UIFont fontWithName:@"Avenir-Medium" size:12.0];
    [chartView strokeChart];
    [self.pieChartUnderView addSubview:chartView];

}
- (void)reloadData{
    //1.设置本单位的data
    self.totalPerLb.text = [NSString stringWithFormat:@"%ld", self.myUnit.myUnitOnDuty.onlinePer.totalPer];
    self.pcPer.text = [NSString stringWithFormat:@"%ld", self.myUnit.myUnitOnDuty.onlinePer.pCPer];
    self.unitSubmissionLb.text = [NSString stringWithFormat:@"%ld", self.myUnit.infoSubmission.unitSubmission];
    self.infoAcceptedLb.text = [NSString stringWithFormat:@"%ld", self.myUnit.infoSubmission.infoAccepted];
    

    //2.下辖单位的data
    
    //2.1在岗情况
    
    //2.2信息报送
    //总体上报信息
    self.totalSubmissionLb.text = [NSString stringWithFormat:@"%ld",self.subordinateUnit.subordinateSubmission.totalSubmission];
    
    //被采分
    self.subInfoAcceptedLb.text = [NSString stringWithFormat:@"%ld",self.subordinateUnit.subordinateSubmission.infoAccepted];
    //得分top3
    if (self.subordinateUnit.subordinateSubmission.submissionScoreTop.count) {
        KDSubmissionUnit *unit1 = self.subordinateUnit.subordinateSubmission.submissionScoreTop[0];
        
        self.top1ScoreLb.text = [NSString stringWithFormat:@"%ld条", unit1.mark];
        self.top1UnitLb.text = unit1.check_desc;
        
        KDSubmissionUnit *unit2 = self.subordinateUnit.subordinateSubmission.submissionScoreTop[1];
        self.top2ScoreLb.text = [NSString stringWithFormat:@"%ld条", unit2.mark];
        self.top2UnitLb.text = unit2.check_desc;
        
        KDSubmissionUnit *unit3 = self.subordinateUnit.subordinateSubmission.submissionScoreTop[2];
        self.top3ScoreLb.text = [NSString stringWithFormat:@"%ld条", unit3.mark];
        self.top3unitLb.text = unit3.check_desc;
    }else{
        self.top1ScoreBtn.selected = YES;
    }
    
    
    //上报信息条数TOP3
    [self setupPieChartView];
    
    //3.0志愿者
    
}
#pragma mark - 事件点击区

#pragma mark - 网络请求区
- (void)loadData{
    KDCalendarParam *param = [[KDCalendarParam alloc]init];
    param.method = @"calendar/unitSimpleInfo";
    param.snapDate = self.selectDateStr;
    [KDManageRequestTool getCalendarWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.status isEqualToString:@"1"]) {
            self.myUnit = [KDMyUnit objectWithKeyValues:responseObejct.data[@"myUnit"]];
            self.subordinateUnit = [KDSubordinateUnit objectWithKeyValues:responseObejct.data[@"subordinateUnit"]];
            [self reloadData];
        }else if ([responseObejct.status isEqualToString:@"-2"]){//还没有登录，或者登录已超时
            KDNewfeatureController *new  = [[KDNewfeatureController alloc]init];
            __block UIViewController *ctr = [UIApplication sharedApplication].keyWindow.rootViewController;
            [UIApplication sharedApplication].keyWindow.rootViewController = new;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                ctr = nil;
            });
        }
    } failure:^(NSError *error) {
        KDLog(@"%@",error);
    }];
}


#pragma mark - 通知接收区



#pragma mark - FSCalendarDataSource
- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    NSComparisonResult result = [date compare:[NSDate date]];
    KDLog(@"%ld", (long)result);
    if (result == 1) {
        [SVProgressHUD showInfoWithStatus:@"选中日期不能大于今日" maskType:SVProgressHUDMaskTypeGradient];
        return NO;
    }else{
        self.selectDateStr = [self.fmt stringFromDate:date];
        [self loadData];
         return YES;
    }
}
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    
    
    
}

- (void)calendar:(FSCalendar *)calendar boundingRectWillChange:(CGRect)bounds animated:(BOOL)animated
{
    _calendarHeightConstraint.constant = CGRectGetHeight(bounds);
//    _calendarWidthConstraint.constant= screenW;
    [self.view layoutIfNeeded];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.lastContentOffset = scrollView.contentOffset.y;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
//    KDLog(@"%f", scrollView.contentOffset.y);
    if (self.lastContentOffset < scrollView.contentOffset.y) {//方便收缩
        KDLog(@"向上滚动");
         [_calendar setScope:FSCalendarScopeWeek animated:YES];
        [self.view setNeedsLayout];
//        KDLog(@"self.tabBarController.tabBar.y: %f", self.tabBarController.tabBar.y);

        
    }else{

    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger yOffset = scrollView.contentOffset.y;
    UITabBar *tb = self.tabBarController.tabBar;
    if (yOffset > 0) {//视情况隐藏tabar
        [UIView animateWithDuration:0.5 animations:^{
            tb.y = self.originalTabY + yOffset;
        }];
    }
    if (yOffset < self.lastContentOffset) {
        [UIView animateWithDuration:0.5 animations:^{
            tb.y = self.originalTabY;
        }];
    }
    if(yOffset < -50){//但是要给下拉制造一点点力度阻碍
//        KDLog(@"向下滚动");
        [_calendar setScope:FSCalendarScopeMonth animated:YES];
//        [self.view layoutIfNeeded];
    }
}

@end
